import { Request, Response, NextFunction } from 'express'
import { Injectable, NestMiddleware } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { IJwtData } from '../typings'

@Injectable()
export class JwtMiddleware implements NestMiddleware {

  constructor(
    private readonly jwtService: JwtService
  ) { }

  use(req: Request, res: Response, next: NextFunction) {
    if (req.headers.authorization) {
      let jwt = this.jwtService.decode(req.headers.authorization)
      if (jwt) {
        req.jwt = jwt as IJwtData
      }
    }
    next()
  }

}
